#!/usr/bin/env python3
# coding=utf-8
import allure
from selenium.webdriver.common.by import By


class WebdriverAction(object):
    ACTION_STEP = 1

    def __init__(self, driver):
        self._driver = driver

    @allure.step("步骤%s:打开{url}" % ACTION_STEP)
    def get_url(self, url):
        WebdriverAction.ACTION_STEP = WebdriverAction.ACTION_STEP + 1
        self._driver.get(url)

    @allure.step("步骤%s:向元素{locator}输入文本 {text}" % str(ACTION_STEP))
    def input_text(self, locator, text):
        WebdriverAction.ACTION_STEP = WebdriverAction.ACTION_STEP + 1
        element = self._find_by_element(locator=locator)
        element.clear()
        element.send_keys(text)

    @allure.step("步骤%s:点击元素 {locator}" % str(ACTION_STEP))
    def click_element(self, locator):
        WebdriverAction.ACTION_STEP = WebdriverAction.ACTION_STEP + 1
        element = self._find_by_element(locator=locator)
        element.click()

    def _find_by_element(self, locator):
        if "=>" in locator:
            locator_type, locator_value = locator.split("=>")

        if "id" == locator_type:
            element = self._driver.find_element_by_id(locator_value)
        elif "name" == locator_type:
            element = self._driver.find_element_by_name(locator_value)
        elif "css" == locator_type:
            element = self._driver.find_element(by=By.CSS_SELECTOR, value=locator_value)
        elif "class" == locator_type:
            element = self._driver.find_element(by=By.CLASS_NAME, value=locator_value)
        elif "tag" == locator_type:
            element = self._driver.find_element(by=By.TAG_NAME, value=locator_value)
        elif "link_text" == locator_type:
            element = self._driver.find_element(by=By.LINK_TEXT, value=locator_value)
        elif "xpath" == locator_type:
            element = self._driver.find_element(by=By.XPATH, value=locator_value)
        else:
            element = self._driver.find_element(by=By.XPATH, value=locator_value)
        return element
